<?php

class ViewCheckpointController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
//			array('allow',  // allow all users to perform 'index' and 'view' actions
//				'actions'=>array('index','view'),
//				'users'=>array('*'),
//			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','index','view','barcode'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
        
        public function getStatusParkir($data)
        {
            if($data->statusParkir == 1)
                $status = "Timbangan";
            elseif($data->statusParkir == 2 || $data->statusParkir == 5)
                $status = "Parking In";
            elseif($data->statusParkir == 3)
                $status = "Assign Gate";
            else
                $status = "Parking Out";
            
            return $status;
        }
        
        public function findNotes($data)
        {
            $c = new CDbCriteria();
            $c->condition = 'tb_monitoring_id=:id';
            $c->params = array(':id' => $data->id);
            $count = Notes::model()->count($c);
            if($count !== '0')
                $icon = '<span class="badge">'.$count.'</span>';
            else 
                $icon = '';
            return $icon;
        }
        
        public function actionBarcode()
	{
		$model=new Kartu;
                
                    $transaction = Yii::app()->db->beginTransaction();
                    try {
                        $model->attributes=$_POST['ViewCheckpoint'];
                        $checkpoint = ViewCheckpoint::model()->findByAttributes(array('noTiket' => $model->noTiket));
                        if(!empty($checkpoint))
                        {
                            if(($checkpoint->statusParkir == 1) && (Yii::app()->user->isParking() || Yii::app()->user->isAdmin()))
                                $this->redirect(array('monitoring/update', 'id'=>$checkpoint->id)); //Confirm Parking
                            elseif(($checkpoint->statusParkir == 2) && (Yii::app()->user->isWarehouse() || Yii::app()->user->isAdmin()))
                                $this->redirect(array("bongkarmuat/update","id"=>$checkpoint->tb_bongkar_muat_id)); //Assign gate
                            elseif(($checkpoint->statusParkir == 3) && (Yii::app()->user->isWarehouse() || Yii::app()->user->isAdmin()))
                                $this->redirect(array("bongkarmuat/load","id"=>$checkpoint->tb_bongkar_muat_id)); //Confirm Un/Load end
                            elseif(($checkpoint->statusParkir == 5) && (Yii::app()->user->isExpedition() || Yii::app()->user->isAdmin()))
                              $this->redirect(array("ekspedisi/create","id"=>$checkpoint->tb_bongkar_muat_id)); //Insert SJ
                            elseif(($checkpoint->statusParkir == 4) && (Yii::app()->user->isWeigher() || Yii::app()->user->isAdmin()))
                                $this->redirect(array("monitoring/out","id"=>$checkpoint->id)); //Mobil out
                            else
                            {
                              Yii::app()->user->setFlash('error', 'Anda tidak memiliki hak untuk menjalankan perintah ini.');
                              $this->redirect(array('viewcheckpoint/'));
                            }
                              
                        }
                        else
                        {
                            Yii::app()->user->setFlash('error', 'Data tidak ditemukan');
                        }
                                        
                    }
                    catch (Exception $e)
                    {
                        $transaction->rollBack();
                        Yii::app()->user->setFlash('error', "{$e->getMessage}");
                    }
	}
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$model=new ViewCheckpoint('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['ViewCheckpoint']))
			$model->attributes=$_GET['ViewCheckpoint'];

                $monitorings = Monitoring::model()->findAll();
                foreach ($monitorings as $monitoring) {
                    $now = date('Y-m-d', time());
                    $created = date('Y-m-d', strtotime($monitoring->created));
                    if(($monitoring->timbanganKeluar == 0) && ($created !== $now))
                    {
                        $bongkarMuat = BongkarMuat::model()->findByAttributes(array('tb_monitoring_id' => $monitoring->id));
                        $gudang = Gudang::model()->findByPk($bongkarMuat->ref_gudang_id);
                        if(!empty($gudang))
                        {
                            $gudang->status = 0;
                            $gudang->save();
                        }
                        $monitoring->delete();
                    }
                }
                $this->render('index',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=ViewCheckpoint::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
        
	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='barcode-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
